package longyiqun.killwife.controller;

import longyiqun.killwife.entity.DeleteResponse;
import longyiqun.killwife.entity.User;
import longyiqun.killwife.util.UserRepository;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * Created by longyiqun on 07/03/2017.
 */

@RestController
public class ApiController {

    // 全局 Repository
    @Autowired
    private UserRepository userRepository;

    // GET 方法 根据ID来查找用户
    @RequestMapping(value = "/api/user/get/id/{id}", method = RequestMethod.GET)
    public ResponseEntity<User> getUserByID(@PathVariable("id") int id) {
        User user = userRepository.findByID(id);
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    // GET 方法 根据name来查找用户
    @RequestMapping(value = "/api/user/get/name/{name}", method = RequestMethod.GET)
    public ResponseEntity<List<User>> getUserByName(@PathVariable("name") String name) {
        List<User> users = userRepository.findByName(name);
        return new ResponseEntity<>(users, HttpStatus.OK);
    }

    // POST 方法 新加一个用户, 传入的JSON为用户的类的形式
    @RequestMapping(value = "api/user/add", method = RequestMethod.POST)
    public ResponseEntity<User> addUser (@RequestBody User user){
        userRepository.save(user);
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    // DELETE 方法 根据ID删除一个用户
    @RequestMapping(value = "api/user/delete/id/{id}", method = RequestMethod.DELETE)
    public DeleteResponse deleteUser (@PathVariable("id") int id ){
        int returnCode = userRepository.deleteByID(id);

        DeleteResponse deleteResponse = new DeleteResponse();
        deleteResponse.code = DeleteResponse.Result.SUCCESS.getCode();
        deleteResponse.message = DeleteResponse.Result.SUCCESS.getMessage();
        return deleteResponse;
    }

    // PUT 方法 更新一个用户的信息
    @RequestMapping(value = "api/user/update", method = RequestMethod.PUT)
    public ResponseEntity<User> updateUser (@RequestBody User user){
        userRepository.updateUser(user.getName(), user.getAge(), user.getId());
        return ResponseEntity.ok(user);
    }
}
